package cn.schoolwow.starter.quickdao;

import cn.schoolwow.quickdao.QuickDAO;
import cn.schoolwow.quickdao.dao.DAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.TransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(QuickDAOProperties.class)
public class QuickDAOConfiguration {
    @Resource
    private QuickDAOProperties quickDAOProperties;

    @Bean
    @Autowired
    public DAO quickdao(DataSource dataSource){
        QuickDAO quickDAO = QuickDAO.newInstance().dataSource(dataSource);
        if(null!=quickDAOProperties.getPackageNameList()){
            for(String packageName:quickDAOProperties.getPackageNameList()){
                quickDAO.packageName(packageName);
            }
        }
        if(null!=quickDAOProperties.getEntityList()){
            for(Class entity:quickDAOProperties.getEntityList()){
                quickDAO.entity(entity);
            }
        }
        if(null!=quickDAOProperties.getIgnorePackageName()){
            for(String packageName:quickDAOProperties.getIgnorePackageName()){
                quickDAO.ignorePackageName(packageName);
            }
        }
        if(null!=quickDAOProperties.getIgnoreClass()){
            for(Class ignoreClass:quickDAOProperties.getIgnoreClass()){
                quickDAO.ignoreClass(ignoreClass);
            }
        }
        if(null!=quickDAOProperties.getEngine()){
            quickDAO.engine(quickDAOProperties.getEngine());
        }
        if(null!=quickDAOProperties.getCharset()){
            quickDAO.charset(quickDAOProperties.getCharset());
        }

        DAO dao = quickDAO
                .autoCreateTable(quickDAOProperties.isAutoCreateTable())
                .autoCreateProperty(quickDAOProperties.isAutoCreateProperty())
                .foreignKey(quickDAOProperties.isForeignKey())
                .build();
        return dao;
    }

    @Bean
    @Autowired
    public TransactionManager transactionManager(DAO dao){
        TransactionManager quickDAOTransactionManager = new QuickDAOTransactionManager(dao);
        return quickDAOTransactionManager;
    }
}